package config

import (
	"fmt"
	"time"
)

type MarketConfig struct {
	Subscriptions   []SubscriptionConfig `yaml:"subscriptions"`     // 订阅配置
	WecomWebhookURL string               `yaml:"wecom_webhook_url"` // 企业微信 webhook
}

type SubscriptionConfig struct {
	InstID string       `yaml:"inst_id"`
	Alerts AlertsConfig `yaml:"alerts"`
}

type AlertsConfig struct {
	PriceChange PriceChangeAlert `yaml:"price_change"`
}

type PriceChangeAlert struct {
	Threshold float64 `yaml:"threshold"`
	Interval  string  `yaml:"interval"`
}

type RuntimePriceChangeAlert struct {
	Threshold float64
	Interval  time.Duration
}

func (p PriceChangeAlert) ToRuntime() (*RuntimePriceChangeAlert, error) {
	duration, err := time.ParseDuration(p.Interval)
	if err != nil {
		return nil, fmt.Errorf("invalid interval format: %v", err)
	}
	return &RuntimePriceChangeAlert{
		Threshold: p.Threshold,
		Interval:  duration,
	}, nil
}

func (c MarketConfig) Validate() error {
	for _, sub := range c.Subscriptions {
		if _, err := time.ParseDuration(sub.Alerts.PriceChange.Interval); err != nil {
			return fmt.Errorf("invalid interval format in subscription %s: %v", sub.InstID, err)
		}
	}
	return nil
}
